import { createApp } from 'vue'
import App from './App.vue'
import router from './router';
import { IonicVue } from '@ionic/vue';
import { LocalNotifications } from '@capacitor/local-notifications';

//import { PushNotifications } from '@capacitor/push-notifications';
import '@capacitor/push-notifications';

/* Core CSS required for Ionic components to work properly */
import '@ionic/vue/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/vue/css/normalize.css';
import '@ionic/vue/css/structure.css';
import '@ionic/vue/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/vue/css/padding.css';
import '@ionic/vue/css/float-elements.css';
import '@ionic/vue/css/text-alignment.css';
import '@ionic/vue/css/text-transformation.css';
import '@ionic/vue/css/flex-utils.css';
import '@ionic/vue/css/display.css';

/**
 * Ionic Dark Mode
 * -----------------------------------------------------
 * For more info, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

/* @import '@ionic/vue/css/palettes/dark.always.css'; */
/* @import '@ionic/vue/css/palettes/dark.class.css'; */
import '@ionic/vue/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';
import axios from 'axios';
import { Preferences } from '@capacitor/preferences';






const INACTIVITY_TIMEOUT = 7 * 24 * 60 * 60 * 1000; 
const app = createApp(App)
  .use(IonicVue)
  .use(router)


  router.isReady().then(() => {
    app.mount('#app');
    startInactivityTimer();
    window.handleNativeNavigation = (routeName: string, params: Record<string, any>) => {
      router.push({ 
        name: routeName,
        params: params
      });
    };
  });

  function startInactivityTimer() {
    setInterval(() => {
      const lastActive = localStorage.getItem('lastActiveTime');
      const isLoggedIn = localStorage.getItem('accessToken');
      
      if (isLoggedIn && lastActive) {
        const diff = Date.now() - parseInt(lastActive);
        if (diff > INACTIVITY_TIMEOUT) {
          app.config.globalProperties.$user.logout();
        }
      }
    }, 60 * 1000); // 每分钟检查一次
  }

  app.config.globalProperties.$user = {
    getInfo: () => JSON.parse(localStorage.getItem('userInfo') || '{}'),
    logout: () => {
      localStorage.removeItem('accessToken');
      localStorage.removeItem('roleIds');
      localStorage.removeItem('userId');
      localStorage.removeItem('roleInfo');
      localStorage.removeItem('roleId');
      localStorage.removeItem('roleName');
      localStorage.removeItem('userRole');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('lastActiveTime'); 
      Preferences.set({ key: 'isLoggedIn', value: 'false' }); // 清除登录状态
      router.push('/login');
    }
  };
  axios.interceptors.response.use(
    // response => response,
    config => {
      localStorage.setItem('lastActiveTime', Date.now().toString());
      return config;
    },
    error => {
      if (error.response?.status === 401) {
        // 清除无效 Token 并跳转
        localStorage.removeItem('accessToken');
        localStorage.removeItem('userId');
        localStorage.removeItem('roleIds');
        localStorage.removeItem('roleInfo');
        localStorage.removeItem('roleId');
        localStorage.removeItem('roleName');
        localStorage.removeItem('userRole');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('displayRoleName');
        Preferences.set({ key: 'isLoggedIn', value: 'false' }); // 清除登录状态
        router.push('/login');
      }
      return Promise.reject(error);
    }
  );

// 请求本地通知权限
const requestNotificationPermissions = async () => {
  try {
    // 调用 LocalNotifications 的 requestPermissions 方法请求权限
    const permissionStatus = await LocalNotifications.requestPermissions();
    // 检查是否获得权限
    if (permissionStatus?.display === 'granted') {
      console.log('本地通知权限已授予');
    } else {
      console.log('本地通知权限被拒绝');
    }
  } catch (error) {
    // 捕获并打印请求权限过程中可能出现的错误
    console.error('请求本地通知权限时出错:', error);
  }
};

// 调用请求权限的函数
requestNotificationPermissions();



// // App.addListener('appUrlOpen', ({ url }) => {
// //   const alertId = url.split('//alerts/')[1];
// //   if (alertId) {
// //     router.push(`/alerts/${alertId}`);
// //   }
// // });